package com.jfinal.config;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.druid.DruidPlugin;


/**
 * DruidPlugin工具类
 * <p>
 * Created by CHEN on 2017/3/18.
 */
public class DruidPluginKit {

    private static final Log LOG = Log.getLog(DruidPluginKit.class);

    public static DruidPlugin create() {
        return create("");
    }

    public static DruidPlugin create(String dbName) {
        String prefix = "mysql";
        if (StrKit.notBlank(dbName)) {
            prefix = prefix + "." + dbName;
        }
        return createByPrefix(prefix);
    }

    public static DruidPlugin createByPrefix(String prefix) {
        String url = PropKit.get(prefix + ".url");
        String username = PropKit.get(prefix + ".username");
        String password = PropKit.get(prefix + ".password");
        String driverClass = PropKit.get(prefix + ".driverClass");

        if (StrKit.isBlank(url)) {
            throw new RuntimeException("url could not be null: " + prefix);
        }

        if (StrKit.isBlank(username)) {
            throw new RuntimeException("username could not be null: " + prefix);
        }

        LOG.info("create druid plugin : " + url);

        DruidPlugin druidPlugin = new DruidPlugin(url, username, password, driverClass);

        Integer initialSize = PropKit.getInt(prefix + ".pool.initialSize");
        if (initialSize != null && initialSize > 0) {
            druidPlugin.setInitialSize(initialSize);
        }

        Integer minIdle = PropKit.getInt(prefix + ".pool.minIdle");
        if (minIdle != null && minIdle > 0) {
            druidPlugin.setMinIdle(minIdle);
        }

        Integer maxActive = PropKit.getInt(prefix + ".pool.maxActive");
        if (maxActive != null && maxActive > 0) {
            druidPlugin.setMaxActive(maxActive);
        }

        Integer maxSize = PropKit.getInt(prefix + ".pool.maxSize");
        if (maxSize != null && maxSize > 0) {
            druidPlugin.setMaxPoolPreparedStatementPerConnectionSize(maxSize);
        }

        Boolean testWhileIdle = PropKit.getBoolean(prefix + ".testWhileIdle", false);
        druidPlugin.setTestWhileIdle(testWhileIdle);

        String validationQuery = PropKit.get(prefix + ".validationQuery");
        druidPlugin.setValidationQuery(validationQuery);

        return druidPlugin;
    }
}
